/**
 * 
 */
package com.zxl.tsc.login.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxl.tsc.login.bean.User;
import com.zxl.tsc.login.service.UserService;
import com.zxl.tsc.util.Encodes;
import com.zxl.tsc.util.constants.Constants;

@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService uesrService;

	@ResponseBody
	@RequestMapping("/regUser")
	public ModelAndView regUser(ModelAndView model, User user) {
		logger.info(user.getLoginName() + "请求注册用户");
		if (uesrService.checkUser(user.getLoginName())) {
			try {
				uesrService.regUser(user);
				model.addObject("msg", "注册成功");
				logger.info(user.getLoginName() + "注册成功");
			} catch (Exception e) {
				logger.error(e.getMessage());
				model.addObject("msg", e + "服务器内部错误");
			}
		} else {
			model.addObject("msg", "用户已存在");
		}
		return model;
	}
	
	@RequestMapping("/pwdPage")
	public ModelAndView pwdPage(ModelAndView model) {
		model.setViewName("login/pwd");
		return model;
	}
	
	@ResponseBody
	@RequestMapping("/changePwd")
	public ModelAndView changePwd(ModelAndView model,@RequestParam String oldpwd , @RequestParam String newpwd,HttpServletRequest request) {
		String userName = (String)request.getSession().getAttribute(Constants.USER_INFO);
		if(userName != null) {
			User user = uesrService.getOneUser(userName);
			if(user != null) {
				if(Encodes.validatePassword(oldpwd, user.getPassword())) {
//					logger.info(oldpwd);
//					logger.info(newpwd);
//					logger.info(String.valueOf(user.getUser_id()));
					uesrService.updatePwd(newpwd,user.getUser_id());
					model.addObject("msg","密码更新成功！");
				}else {
					model.addObject("msg", "更新失败！原密码不正确！");
				}
			}else {
				logger.info("用户信息查找失败");
			}
		}else {
			model.addObject("msg", "服务器内部错误，请重新登陆！");
		}
		return model;
	}

}
